package com.es.disped.web.controller.oj.judgeproblem;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.es.disped.api.oj.solution.HustSolutionService;
import com.es.disped.api.oj.sourcecode.HustSourceCodeService;
import com.es.disped.api.oj.sourcecodeuser.HustSourceCodeUserService;
import com.es.disped.common.annotation.DynamicDataSource;
import com.es.disped.common.model.MsgModel;
import com.es.disped.core.controller.BaseController;
import com.es.disped.dao.oj.model.Solution;
import com.es.disped.dao.oj.model.SourceCode;
import com.es.disped.dao.oj.model.SourceCodeUser;
import com.es.disped.dao.oj.model.SubmitProbDefunct;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author Anson<br>
 *	Copyright by EasyShare 2019<br>
 *  
 *  All right reserved<br>
 *
 *  Created on 2019年7月19日 下午1:49:08<br>
 *  名称：JudgeProblemController.java<br>
 *  描述：OJ判题<br>
 */
@Api("OJ判题")
@Controller
@RequestMapping("/oj/judge")
public class JudgeProblemController extends BaseController{
	
	private final String NAMESPACE="com.es.disped.dao.mapper.judge.JudgeCustomMapper";

	@Autowired
	HustSolutionService hustSolutionService;
	@Autowired
	HustSourceCodeService hustSourceCodeService;
	@Autowired
	HustSourceCodeUserService hustSourceCodeUserService;
	
	@ApiOperation(value="提交题目",response=MsgModel.class,httpMethod="POST",
			notes="OJ判题，问题列表与作业题目提交参数不同：问题列表，问题ID，语言，源码；作业：作业ID，问题在作业中的序号值，语言，源码")
	@RequestMapping(value="/submit",method=RequestMethod.POST)
	@DynamicDataSource
	public @ResponseBody MsgModel submit(@RequestBody @ApiParam(name="paramMap",value="判题序列对象",required=true) Map<String, Object> paramMap)
	{
		int count=0;
		SubmitProbDefunct submitProbDefunct=null;
		if(paramMap.containsKey("id"))
		{
			submitProbDefunct=this.getHustService().selectOne(NAMESPACE+".getProbDefunctById", paramMap.get("id"));
		}else if(paramMap.containsKey("cid")&&paramMap.containsKey("pid"))
		{
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("cid", paramMap.get("cid"));
			map.put("pid", paramMap.get("pid"));
			submitProbDefunct=this.getHustService().selectOne(NAMESPACE+".getProbDefunctByParams", map);
		}
		if(this.isNull(submitProbDefunct))
		{
			return this.resultMsg(HttpStatus.NOT_FOUND.value(), "所提交的题目不存在");
		}
		if(!this.isNull(submitProbDefunct)&&!submitProbDefunct.getDefunct().equals("N"))
		{
			return this.resultMsg(HttpStatus.UNAVAILABLE_FOR_LEGAL_REASONS.value(), "题目被禁用");
		}
		Integer res=this.getHustService().selectOne(NAMESPACE+".getProblastSubmit", this.getSessionUser().getPhone());
		if(res==1)
		{
			return this.resultMsg(HttpStatus.FORBIDDEN.value(), "题目提交过于频繁");
		}
		
		String source=paramMap.get("source").toString();
		source=source.replaceAll("\r\n", "\n");
		
		Solution solution=new Solution();
		solution.setProblemId(submitProbDefunct.getProblemId());
		solution.setUserId(this.getSessionUser().getPhone());
		solution.setInDate(new Date());
		solution.setLanguage(Integer.valueOf(paramMap.get("language").toString()));
		solution.setIp(this.getRequest().getRemoteAddr());
		solution.setCodeLength(source.length());
		solution.setResult((short)14);
		if(paramMap.containsKey("cid")&&paramMap.containsKey("pid"))
		{
			solution.setContestId(Integer.valueOf(paramMap.get("cid").toString()));
			solution.setNum(Byte.valueOf(paramMap.get("pid").toString()));
		}
		//保存提交记录
		count+=hustSolutionService.insertSelective(solution);
		//查询记录ID
		Map<String, Object> soMap=new HashMap<String, Object>();
		soMap.put("userId", this.getSessionUser().getPhone());
		soMap.put("problemId", submitProbDefunct.getProblemId());
		Integer solutionId=this.getHustService().selectOne(NAMESPACE+".getLastSubmitsoId", soMap);
		//保存提交源码
		SourceCode sourceCode=new SourceCode();
		sourceCode.setSolutionId(solutionId);
		sourceCode.setSource(source);
		count+=hustSourceCodeService.insert(sourceCode);
		SourceCodeUser sourceCodeUser=new SourceCodeUser();
		sourceCodeUser.setSolutionId(solutionId);
		sourceCodeUser.setSource(source);
		count+=hustSourceCodeUserService.insert(sourceCodeUser);
		//修改result为0，开始判题
		Solution updateSolution=new Solution();
		updateSolution.setResult((short)0);
		updateSolution.setSolutionId(solutionId);
		hustSolutionService.updateByPrimaryKeySelective(updateSolution);
		return this.resultMsg(count>1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count>1?"提交成功":"提交失败",count>1?solutionId:"");
	}
	
	
	@ApiOperation(value="获取判题结果",response=MsgModel.class,httpMethod="POST",notes="OJ判题结果")
	@RequestMapping(value="/status",method=RequestMethod.POST)
	@DynamicDataSource
	public @ResponseBody MsgModel status(@RequestBody @ApiParam(name="solution",value="判题结果对象",required=true) Solution solution)
	{
		Solution res=this.getHustService().selectOne(NAMESPACE+".getJudgeStatus", solution.getSolutionId());
		return this.resultMsg(!this.isNull(res)?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				!this.isNull(res)?"加载成功":"获取失败",!this.isNull(res)?res:"");
	}
}
